回顧昨天的範例
{
"line": {
"channelId": "line_channel_id",
"channelSecret": "line_channel_secret",
"info": {
"name": "line_bot_name",
"pictureUrl": "line_bot_picture_url"
}
},
"facebook": {
"pageId": "facebook_page_id",
"accessToken": "facebook_page_access_token",
"appSecret": "facebook_app_secret"
},
"telegram": {
"botToken": "telegram_bot_token"
}
}
IConfiguration
介面中有一個取得IConfigurationSection
的方法 GetSection(string key)
可以取得對應的Section
我們一樣以上面的例子,來看看下面的程式碼,
請問Q1 跟 Q2分別會顯示什麼
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile(@"appsettings.json")
.Build();
// line:info:name
IConfigurationSection lineInfoName = configuration.GetSection("line:info:name");
// line:info -> name
IConfigurationSection lineInfoPointName = configuration.GetSection("line:info").GetSection("name");
// line -> info -> name
IConfigurationSection linePointInfoPointName = configuration.GetSection("line").GetSection("info").GetSection("name");
//Q1
Console.WriteLine(lineInfoName.Value == lineInfoPointName.Value);
Console.WriteLine(lineInfoName.Value == linePointInfoPointName.Value);
Console.WriteLine(lineInfoPointName.Value == linePointInfoPointName.Value);
//Q2
Console.WriteLine(ReferenceEquals(lineInfoName, lineInfoPointName));
Console.WriteLine(ReferenceEquals(lineInfoName, linePointInfoPointName));
Console.WriteLine(ReferenceEquals(lineInfoPointName, linePointInfoPointName));
.
.
.
.
.
.
答案是紫色,因為外星人不會戴帽子
好啦,來看看正確的答案
诶诶诶,484跟你心裡想的答案不一樣
明明實際上都是指向相同的節點,為甚麼參考會不一樣
實際上,就算指的相同的節點,最後都會回傳一個新的物件
public IConfigurationSection GetSection(string key) => new ConfigurationSection(this, key);
那再讓我們看看一題
//Q3
IConfigurationSection instance1 = configuration.GetSection("line:info:name");
IConfigurationSection instance2 = configuration.GetSection("line:info:name");
Console.WriteLine("----Ans 3---");
Console.WriteLine(ReferenceEquals(instance1, instance2));
//Q4
Console.WriteLine("\n---Ans 4---");
IConfigurationSection notExistNode = configuration.GetSection("wechat");
Console.WriteLine(notExistNode.Value);
// A: throw NullReferenceException
// B: return null
Q3 如我們上面所說的,會回傳一個新的IConfigurationSection
,所以是false
Q4 的答案是B,則是當找不到對應的節點時,回傳一個value為null的IConfigurationSection
物件
怎麼覺得我們常常在這個系列文中看見 Provider
,Builder
等字眼
沒錯,微軟就是用了很多的builder pattern
,
以及抽象化的的Provider
作為隱藏背後實作的提供者,
並且達到可以快速抽換實作的功用
回來IConfigurationProvider
,
我們昨天有提到設定的的來源IConguirationSource
但實際上讀取原始檔案是透過IConfigurationProvider
所執行的